package org.jeecg.modules.mes.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataReplacematerial;
import org.jeecg.modules.mes.client.ProduceClient;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.client.TransactionClient;
import org.jeecg.modules.mes.order.entity.MesOrderProduce;
import org.jeecg.modules.mes.order.entity.MesPurchaseItem;
import org.jeecg.modules.mes.produce.entity.MesCommandbillInfo;
import org.jeecg.modules.mes.produce.entity.MesCommandbillPitem;
import org.jeecg.modules.mes.storage.entity.*;
import org.jeecg.modules.mes.storage.mapper.MesStorageWholesaleMapper;
import org.jeecg.modules.mes.storage.service.*;
import org.jeecg.modules.mes.storage.utils.AsyncUtils;
import org.jeecg.modules.mes.storage.vo.ReportVo;
import org.jeecg.modules.mes.storage.vo.YclJxcReportVO;
import org.jeecg.modules.mes.storage.vo.YclRkdReport;
import org.jeecg.modules.mes.storage.vo.YclRkdReportVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 仓库管理—批号交易
 * @Author: jeecg-boot
 * @Date: 2020-09-14
 * @Version: V1.0
 */
@Slf4j
@Service
public class MesStorageWholesaleServiceImpl extends ServiceImpl<MesStorageWholesaleMapper, MesStorageWholesale> implements IMesStorageWholesaleService {


    @Autowired
    private IMesCertificateItemService mesCertificateItemService;
    @Autowired
    private IMesStockManageService mesStockManageService;
    @Autowired
    private IMesCertificatePerkService mesCertificatePerkService;
    @Autowired
    private MesStorageWholesaleMapper mesStorageWholesaleMapper;
    @Autowired
    private AsyncUtils asyncUtils;
    @Autowired
    TransactionClient transactionClient;
    @Autowired
    SystemClient systemClient;
    @Autowired
    ProduceClient produceClient;
    @Autowired
    private IMesMaterielOccupyService mesMaterielOccupyService;
    @Autowired
    private IMesWarehouseAreaService iMesWarehouseAreaService;

    private Lock lock = new ReentrantLock();

    /**
     * 通过id查询追踪记录
     *
     * @param id
     * @return
     */
    public List<MesStorageWholesale> findByIdTraceBack(String id) {
        return mesStorageWholesaleMapper.findByIdTraceBack(id);
    }

    /**
     * 修改收货状态和未收货数量
     *
     * @param unreceiveNum 未收货数量
     * @param temId        采购订单子表id
     * @return
     */
    public boolean updateNumStatePurchaseItemId(String unreceiveNum, String temId) {
        return retBool(mesStorageWholesaleMapper.updateNumStatePurchaseItemId(unreceiveNum, temId));
    }


    /**
     * 修改未收货数量
     *
     * @param unreceiveNum 未收货数量
     * @param temId        采购订单子表id
     * @return
     */
    public boolean updateNumPurchaseItemId(String unreceiveNum, String temId) {
        return retBool(mesStorageWholesaleMapper.updateNumPurchaseItemId(unreceiveNum, temId));
    }


    //    @CacheEvict(key="#query4")//该注解用于删除缓存
    @Override
    @Cacheable(value = CacheConstant.WAREHOUSE_SELECT_QUERY4_SL, key = "#p0")
    public List<MesStorageWholesale> selectQuery4SL(String query4) {
        return mesStorageWholesaleMapper.selectQuery4SL(query4);
    }

    /**
     * app 一键收货
     *
     * @param baseCode   采购订单子表id
     * @param baseRownum 物料凭证项目id
     * @return
     */
    @Transactional
    public void oneTakeDelivery(String baseCode, String baseRownum) {
        MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(baseCode);
        if (purchaseItem == null) {
            throw new RuntimeException("该采购明细数据不存在，请检查！");
        }
        //未收货已打印标签
        List<MesStorageWholesale> mesStorageWholesales = mesStorageWholesaleMapper.selectPrintUnreceivelist(baseCode);
        for (MesStorageWholesale storageWholesale : mesStorageWholesales) {
            modifyinfo(storageWholesale, baseCode, baseRownum, purchaseItem);
        }
    }

    public MesStorageWholesale modifyinfo(MesStorageWholesale mesStorageWholesale, String baseCode, String perkid, MesPurchaseItem purchaseItem) {
        long startTime = System.currentTimeMillis();

        mesStorageWholesale.setQuery4(mesStorageWholesale.getId());
        mesStorageWholesale.setId(null);
        mesStorageWholesale.setBaseDockettype("扫描收货");
        mesStorageWholesale.setBaseCode(baseCode);

        //新增或拿到物料凭证项目
        MesCertificateItem item1 = new MesCertificateItem();
        item1.setInputNum("0");
        item1.setMobileType("扫描收货");
        item1.setMobileCode("103");
        item1.setMaterielCode(purchaseItem.getMaterielCode());//物料内部料号
        item1.setPerkId(perkid);//抬头id
        item1.setReserveCode(baseCode);//采购订单子表id
        MesCertificateItem mesCertificateItem = mesCertificatePerkService.addReceiveItem2(item1);

        mesStorageWholesale.setBaseRownum(mesCertificateItem.getId());//物料凭证项目id

        BigDecimal unreceiveNum = new BigDecimal(purchaseItem.getUnreceiveNum());//未收货数量
        System.out.println("oneTakeDelivery:" + mesStorageWholesale);
        if (StringUtils.isBlank(mesStorageWholesale.getInwareNum())) {//如果入库数量不是空
            mesStorageWholesale.setInwareNum("0");
        }
        BigDecimal receiveNum = new BigDecimal(mesStorageWholesale.getInwareNum());//入库数量
        BigDecimal remainNum = unreceiveNum.subtract(receiveNum);//可收货数量=未收货数量-入库数量
        if ((remainNum.compareTo(BigDecimal.ZERO) == -1) || (remainNum.compareTo(BigDecimal.ZERO) == 0)) {
            System.out.println("==111===" + remainNum.toString() + "===" + purchaseItem.getId());
            mesStorageWholesaleMapper.updateNumPurchaseItemId(remainNum.toString(), purchaseItem.getId());
            //收货完成，异步向工作人员发送质检提醒；
            asyncUtils.asyncSend(purchaseItem);

            String perkId = mesCertificateItem.getPerkId();
            MesCertificatePerk certificatePerk = mesCertificatePerkService.getById(perkId);
            if (certificatePerk != null) {
                certificatePerk.setIfFinish("未完成");
                mesCertificatePerkService.updateById(certificatePerk);
            }
        } else {
            mesStorageWholesaleMapper.updateNumPurchaseItemId(remainNum.toString(), purchaseItem.getId());
            //修改凭证项目的inputNum数量
            MesCertificateItem item = new MesCertificateItem();
            item.setId(mesCertificateItem.getId());
            mesCertificateItemService.updateById(item);
        }
        mesStorageWholesale.setWareCode(purchaseItem.getFactoryCode());//工厂编号
        mesStorageWholesale.setQuery2(purchaseItem.getFactoryName());//工厂名称
        mesStorageWholesale.setWareSite(purchaseItem.getStorageSite());//存储位置
        /*****根据baseRowNum查询出凭证项目更新录入数量和未入库数量****/
        //基本行号：物料凭证项目id
        String pCode = mesStorageWholesale.getProductCode();
        if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {

            String mCode = mesCertificateItem.getMaterielCode();//物料料号
            if (pCode.equals(mCode)) {
                if (StringUtils.isNotBlank(mesStorageWholesale.getInwareNum())) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    if (StringUtils.isBlank(mesCertificateItem.getUnstorageNum())) {
                        mesCertificateItem.setUnstorageNum("0");
                    }
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//录入数量
                    BigDecimal unstorageNum = new BigDecimal(mesCertificateItem.getUnstorageNum());//未入库数量
                    BigDecimal inwareNum = new BigDecimal(mesStorageWholesale.getInwareNum());
                    BigDecimal newInputNum = inputNum.add(inwareNum);
                    BigDecimal newUnstorageNum = unstorageNum.add(inwareNum);
                    mesCertificateItem.setInputNum(newInputNum.toString());
                    mesCertificateItem.setUnstorageNum(newUnstorageNum.toString());
                    mesCertificateItem.setIfInspect("否");
                    mesCertificateItem.setIfStorage("否");
                }
                mesStorageWholesale.setQuery3(mesCertificateItem.getPerkId());//物料凭证项目id
                mesCertificateItemService.updateById(mesCertificateItem);

                //获取凭证抬头信息，判断凭证抬头状态，如果质检完成，修改质检和入库为未完成
                MesCertificatePerk perkinfo = mesCertificatePerkService.getById(mesCertificateItem.getPerkId());
                if (perkinfo != null) {
                    if (StringUtils.isBlank(perkinfo.getIfFinish())) {
                        perkinfo.setIfFinish("未完成");
                    }
                    if (StringUtils.isBlank(perkinfo.getIfInput())) {
                        perkinfo.setIfInput("未完成");
                    }
                    if ("质检完成".equals(perkinfo.getIfFinish())) {
                        perkinfo.setIfFinish("未完成");
                        perkinfo.setIfInput("未完成");
                    }
                    mesCertificatePerkService.updateById(perkinfo);
                }
            } else {
                throw new RuntimeException("扫描的物料不符！请检查！");
            }
        }
        //执行方法
        long endTime = System.currentTimeMillis();
        float excTime = (float) (endTime - startTime) / 1000;
        System.out.println("oneTakeDeliverymodify执行时间：" + excTime + "s");
        mesStorageWholesale.setCreateBy(null);
        mesStorageWholesale.setCreateTime(null);
        this.save(mesStorageWholesale);
        return mesStorageWholesale;
    }

    /**
     * app 扫描收货
     *
     * @param id       批号交易id,二维码id
     * @param baseCode 采购订单子表id
     * @param perkid   物料凭证抬头id
     * @return
     */
    public synchronized MesStorageWholesale addTakeDelivery(String id, String baseCode, String perkid) {
        long startTime = System.currentTimeMillis();

        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("扫描的二维码为空！");
        }
        System.out.println("addTakeDelivery: id:" + id + " baseCode:" + baseCode + " baseRownum:" + perkid);
        MesStorageWholesale mesStorageWholesale = this.getById(id);
        if (mesStorageWholesale == null) {
            throw new RuntimeException("扫描的二维码不存在！");
        } else {
            MesStorageWholesale msw = modify(mesStorageWholesale, baseCode, perkid);
            //执行方法
            long endTime = System.currentTimeMillis();
            float excTime = (float) (endTime - startTime) / 1000;
            System.out.println("addTakeDelivery执行时间：" + excTime + "s");
            return msw;
        }
    }

    @Transactional
    public MesStorageWholesale modify(MesStorageWholesale mesStorageWholesale, String baseCode, String perkid) {
        long startTime = System.currentTimeMillis();
        String mwid=mesStorageWholesale.getId();
        //扫描重复检查
        if (StringUtils.isNotBlank(mesStorageWholesale.getId())) {
            QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("query4", mesStorageWholesale.getId());
            List<MesStorageWholesale> storageWholesales = this.list(queryWrapper);
            if (storageWholesales.size() > 0) {
                throw new RuntimeException("请勿重复扫描！");
            }
        }
        mesStorageWholesale.setQuery4(mwid);
        mesStorageWholesale.setId(null);
        mesStorageWholesale.setBaseDockettype("扫描收货");
        mesStorageWholesale.setBaseCode(baseCode);

        MesPurchaseItem purchaseItem = transactionClient.queryMesPurchaseItemById(baseCode);
        if (purchaseItem == null) {
            throw new RuntimeException("该采购明细数据不存在，请检查！");
        }
        //新增或拿到物料凭证项目
        MesCertificateItem item1 = new MesCertificateItem();
        item1.setInputNum("0");
        item1.setMobileType("扫描收货");
        item1.setMobileCode("103");
        item1.setMaterielCode(purchaseItem.getMaterielCode());//物料内部料号
        item1.setPerkId(perkid);//抬头id
        item1.setReserveCode(baseCode);//采购订单子表id
        MesCertificateItem mesCertificateItem = mesCertificatePerkService.addReceiveItem2(item1);

        mesStorageWholesale.setBaseRownum(mesCertificateItem.getId());//物料凭证项目id

        BigDecimal unreceiveNum = new BigDecimal(purchaseItem.getUnreceiveNum());//未收货数量
        System.out.println("addTakeDelivery:" + mesStorageWholesale);
        if (StringUtils.isNoneBlank(mesStorageWholesale.getInwareNum())) {//如果入库数量不是空
            BigDecimal receiveNum = new BigDecimal(mesStorageWholesale.getInwareNum());//入库数量
            BigDecimal remainNum = unreceiveNum.subtract(receiveNum);//可收货数量=未收货数量-入库数量
            if ((remainNum.compareTo(BigDecimal.ZERO) == -1) || (remainNum.compareTo(BigDecimal.ZERO) == 0)) {
                System.out.println("==111===" + remainNum.toString() + "===" + purchaseItem.getId());
                        /*throw new RuntimeException("请检查收货数量是否正确！");
                    } else if () {*/
                //					purchaseItem.setUnreceiveNum(remainNum.toString());
                //					purchaseItem.setIfFinish("收货完成");
                //					transactionClient.editPurchaseItem(purchaseItem);
//                this.updateNumStatePurchaseItemId(remainNum.toString(), purchaseItem.getId());
                mesStorageWholesaleMapper.updateNumPurchaseItemId(remainNum.toString(), purchaseItem.getId());
                //收货完成，异步向工作人员发送质检提醒；
                asyncUtils.asyncSend(purchaseItem);

                String perkId = mesCertificateItem.getPerkId();
                MesCertificatePerk certificatePerk = mesCertificatePerkService.getById(perkId);
                if (certificatePerk != null) {
                    certificatePerk.setIfFinish("未完成");
                    mesCertificatePerkService.updateById(certificatePerk);
                }
            } else {
                System.out.println("==222===" + remainNum.toString() + "===" + purchaseItem.getId());
                //					purchaseItem.setUnreceiveNum(remainNum.toString());
                //					transactionClient.editPurchaseItem(purchaseItem);
//                this.updateNumPurchaseItemId(remainNum.toString(), purchaseItem.getId());
                mesStorageWholesaleMapper.updateNumPurchaseItemId(remainNum.toString(), purchaseItem.getId());
                //修改凭证项目的inputNum数量
                MesCertificateItem item = new MesCertificateItem();
                item.setId(mesCertificateItem.getId());
                mesCertificateItemService.updateById(item);
            }
        } else {
            throw new RuntimeException("该物料入库数量为空！");
        }
        mesStorageWholesale.setWareCode(purchaseItem.getFactoryCode());//工厂编号
        mesStorageWholesale.setQuery2(purchaseItem.getFactoryName());//工厂名称
        mesStorageWholesale.setWareSite(purchaseItem.getStorageSite());//存储位置
        /*****根据baseRowNum查询出凭证项目更新录入数量和未入库数量****/
        //基本行号：物料凭证项目id
        String pCode = mesStorageWholesale.getProductCode();
        //            MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
        //System.err.println("mesCertificateItem==============="+mesCertificateItem);
        if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {

            String mCode = mesCertificateItem.getMaterielCode();//物料料号
            if (pCode.equals(mCode)) {
                if (StringUtils.isNotBlank(mesStorageWholesale.getInwareNum())) {
                    if (StringUtils.isBlank(mesCertificateItem.getInputNum())) {
                        mesCertificateItem.setInputNum("0");
                    }
                    if (StringUtils.isBlank(mesCertificateItem.getUnstorageNum())) {
                        mesCertificateItem.setUnstorageNum("0");
                    }
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//录入数量
                    BigDecimal unstorageNum = new BigDecimal(mesCertificateItem.getUnstorageNum());//未入库数量
                    BigDecimal inwareNum = new BigDecimal(mesStorageWholesale.getInwareNum());
                    BigDecimal newInputNum = inputNum.add(inwareNum);
                    BigDecimal newUnstorageNum = unstorageNum.add(inwareNum);
                    mesCertificateItem.setInputNum(newInputNum.toString());
                    mesCertificateItem.setUnstorageNum(newUnstorageNum.toString());
                    mesCertificateItem.setIfInspect("否");
                    mesCertificateItem.setIfStorage("否");
                }
                mesStorageWholesale.setQuery3(mesCertificateItem.getPerkId());//物料凭证项目id
                mesCertificateItemService.updateById(mesCertificateItem);

                //获取凭证抬头信息，判断凭证抬头状态，如果质检完成，修改质检和入库为未完成
                MesCertificatePerk perkinfo = mesCertificatePerkService.getById(mesCertificateItem.getPerkId());
                if (perkinfo != null) {
                    if (StringUtils.isBlank(perkinfo.getIfFinish())) {
                        perkinfo.setIfFinish("未完成");
                    }
                    if (StringUtils.isBlank(perkinfo.getIfInput())) {
                        perkinfo.setIfInput("未完成");
                    }
                    if ("质检完成".equals(perkinfo.getIfFinish())) {
                        perkinfo.setIfFinish("未完成");
                        perkinfo.setIfInput("未完成");
                    }
                    mesCertificatePerkService.updateById(perkinfo);
                }
            } else {
                throw new RuntimeException("扫描的物料不符！请检查！");
            }
        }
        //执行方法
        long endTime = System.currentTimeMillis();
        float excTime = (float) (endTime - startTime) / 1000;
        System.out.println("addTakeDeliverymodify执行时间：" + excTime + "s");
        mesStorageWholesale.setCreateBy(null);
        mesStorageWholesale.setCreateTime(null);
        this.save(mesStorageWholesale);
        return mesStorageWholesale;
    }

    /**
     * app 扫描上料
     *
     * @param id        批号交易id,二维码id
     * @param commandId 制令单id
     * @param prekId    物料凭证id
     * @param passage   通道
     * @param feeder    菲达
     * @return
     */
    public MesStorageWholesale addUnglaze(String id, String commandId, String prekId, String passage, String feeder) {
        MesStorageWholesale mesStorageWholesale = new MesStorageWholesale();


        return mesStorageWholesale;
    }

    /**
     * 批量扫描入库
     *
     * @param mesStorageWholesale
     * @return
     */
    @Override
    public synchronized boolean addScanStoreAll(MesStorageWholesale mesStorageWholesale) {
        long startTime = System.currentTimeMillis();

        if (StringUtils.isNotBlank(mesStorageWholesale.getProductCode()) &&
                StringUtils.isNotBlank(mesStorageWholesale.getBaseRownum()) &&
                StringUtils.isNotBlank(mesStorageWholesale.getBaseDockettype())) {
            String pCode = mesStorageWholesale.getProductCode();//产品编号：料号
            System.err.println(pCode);

            String shelfCode = mesStorageWholesale.getShelfCode();//货架编号

            if (!"无货架入库".equals(mesStorageWholesale.getShelfCode())) {
                //验证货架是否状态为0，待发料
                QueryWrapper<MesStorageWholesale> storageQueryWrapper = new QueryWrapper<>();
                storageQueryWrapper.eq("shelf_code", shelfCode);
                storageQueryWrapper.eq("base_dockettype", "收货打印");
                storageQueryWrapper.eq("shelf_state", "0");
                List<MesStorageWholesale> list1 = this.list(storageQueryWrapper);
                if (list1.size() > 0) {
                    throw new RuntimeException("该货位已有物品，请核实！");
                }
            }

            //验证是否有扫描收货记录
            if (StringUtils.isNotBlank(mesStorageWholesale.getId())) {
                String swId = mesStorageWholesale.getId();//扫描过来的物料id
                QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("product_code", pCode).eq("base_dockettype", "扫描收货").eq("query4", mesStorageWholesale.getId());
                List<MesStorageWholesale> list = this.list(queryWrapper);
                if (list.size() == 0) {
                    throw new RuntimeException("该物品未收货，请核实！");
                }
            }
            //验证是否有扫描入库记录
            if (StringUtils.isNotBlank(mesStorageWholesale.getId())) {
                String swId = mesStorageWholesale.getId();//扫描过来的物料id
                QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("product_code", pCode).eq("base_dockettype", mesStorageWholesale.getBaseDockettype()).eq("query4", mesStorageWholesale.getId());
                List<MesStorageWholesale> list = this.list(queryWrapper);
                if (list.size() > 0) {
                    throw new RuntimeException("请勿重复扫描！");
                }
            }

            boolean mark = addScanStoreAllmodify(mesStorageWholesale, shelfCode, pCode);
            //执行方法
            long endTime = System.currentTimeMillis();
            float excTime = (float) (endTime - startTime) / 1000;
            System.out.println("执行addScanStoreAll时间：" + excTime + "s");
            return mark;
        } else {
            throw new RuntimeException("找不到数据！请检查！");
        }
    }

    @Transactional
    public boolean addScanStoreAllmodify(MesStorageWholesale mesStorageWholesale,
                                         String shelfCode, String pCode) {
        long startTime = System.currentTimeMillis();
        //入库二维码
        String gId = mesStorageWholesale.getId();
        // 获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String baseRowNum = mesStorageWholesale.getBaseRownum();//基本行号：物料凭证id
        String docketType = mesStorageWholesale.getBaseDockettype();//单据类型 扫描入库

        //通过物料凭证id,获取物料凭证项目的数据
        QueryWrapper<MesCertificateItem> queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("perk_id", baseRowNum);
        queryWrapper1.eq("if_inspect", "是");//已检验
        queryWrapper1.eq("if_storage", "否");//未入库
        queryWrapper1.eq("mobile_type", "扫描收货");//未入库
        queryWrapper1.eq("materiel_code", mesStorageWholesale.getProductCode());//未入库

        List<MesCertificateItem> certificateItems = mesCertificateItemService.list(queryWrapper1);
        /*if (certificateItems.size() == 0) {
            //通过物料凭证id,获取物料凭证项目的数据
            QueryWrapper<MesCertificateItem> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("perk_id", baseRowNum);
            queryWrapper2.eq("if_inspect", "是");//已检验
            queryWrapper2.eq("mobile_type", "扫描收货");//未入库
            certificateItems = mesCertificateItemService.list(queryWrapper2);
        }*/
        if (certificateItems.size() == 0) {
            throw new RuntimeException("该物品未质检，请检查！");
        }
        //判断是否入库了
        int count = 0;
        for (MesCertificateItem mesCertificateItem : certificateItems) {
            if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {
                String mCode = mesCertificateItem.getMaterielCode();//需要的物料料号
                System.err.println(mCode);
                //扫描重复检查
                if (StringUtils.isNotBlank(shelfCode)) {//判断货架不为空
                    //每扫描成功一个标签，则query04存入该标签的ID，代表该标签已经被扫描过
                    String swId = mesStorageWholesale.getId();//扫描过来的物料id
                    QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("product_code", pCode).eq("base_dockettype", docketType).eq("query4", swId);
                    List<MesStorageWholesale> list = this.list(queryWrapper);
                    System.out.println("size:" + list.size());
                    if (list.size() > 0) {
                        throw new RuntimeException("请勿重复扫描！");
                    } else {

                        if (count == 0 && mCode.equals(mesStorageWholesale.getProductCode())) {//判断料号是否相同，相同则进行下一步操作

                            if (true) {
                                BigDecimal inwareNum = new BigDecimal(mesStorageWholesale.getInwareNum());
                                BigDecimal totalNum = new BigDecimal(mesCertificateItem.getUnstorageNum());
                                BigDecimal unstorageNum = totalNum.subtract(inwareNum);
                                if ((unstorageNum.compareTo(BigDecimal.ZERO) == -1) || (unstorageNum.compareTo(BigDecimal.ZERO) == 0)) {
                                            /*throw new RuntimeException("入库数量不符！请检查！");
                                        } else if (unstorageNum.compareTo(BigDecimal.ZERO) == 0) {*/
                                    mesCertificateItem.setIfStorage("是");
                                    mesCertificateItem.setUnstorageNum(unstorageNum.toString());
                                    mesCertificateItemService.updateById(mesCertificateItem);
                                } else {
                                    mesCertificateItem.setUnstorageNum(unstorageNum.toString());
                                    mesCertificateItemService.updateById(mesCertificateItem);
                                }
                            }
                            if (StringUtils.isNotBlank(mesStorageWholesale.getInwareNum())) {
                                BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//物料凭证已有数量
                                BigDecimal inwareNum = new BigDecimal(mesStorageWholesale.getInwareNum());//标签上的数量
                                BigDecimal newInputNum = inputNum.add(inwareNum);//凭证新数量=已有数量+标签上的数量
                                mesCertificateItem.setInputNum(newInputNum.toString());
                                mesCertificateItem.setUnstorageNum(newInputNum.toString());//未入库数量=凭证新数量
                                //106 扫描入库
                                if ("103".equals(mesCertificateItem.getMobileCode())) {
                                    QueryWrapper<MesStockManage> wrapper = new QueryWrapper<>();
                                    wrapper.eq("materiel_code", mCode);
                                    //修改说明开始：添加区位信息验证，因为库存管理添加了区位信息，所以物料需要按照区位划分
                                    wrapper.eq("area_code", mesStorageWholesale.getAreaCode());
                                    wrapper.eq("location_code", mesStorageWholesale.getLocationCode());
                                    //修改说明结束：添加区位信息验证，因为库存管理添加了区位信息，所以物料需要按照区位划分
                                    MesStockManage stockManage = mesStockManageService.getOne(wrapper);
                                    if (stockManage != null) {
                                        if (StringUtils.isNotBlank(stockManage.getStockNum())) {
                                            if (StringUtils.isNotBlank(stockManage.getStockNum())) {

                                            }
                                            BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                            BigDecimal totalNum = stockNum.add(inwareNum);
                                            stockManage.setStockNum(totalNum.toString());
                                            mesStockManageService.updateById(stockManage);
                                        } else {
                                            throw new RuntimeException("料号为 " + mesCertificateItem.getMaterielCode() + "的" + mesCertificateItem.getMaterielName() + "库存数量不能为空！");
                                        }
                                    } else {
                                        MesStockManage mesStockManage = new MesStockManage();
                                        BeanUtils.copyProperties(mesCertificateItem, mesStockManage);
                                        mesStockManage.setId(null);//主键设置为null
                                        mesStockManage.setCreateBy(sysUser.getUsername());//创建人设置
                                        mesStockManage.setCreateTime(DateUtils.getDate());//创建时间设置
                                        mesStockManage.setStoreName(mesCertificateItem.getStorageSite());
                                        mesStockManage.setUnit(mesCertificateItem.getInputUnit());
                                        mesStockManage.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        mesStockManage.setStockNum(inwareNum.toString());
                                        mesStockManage.setQuery5(mesStorageWholesale.getRowNum());
//                                        mesStockManage.setQuery6(mesCertificateItem.getClientCode());//客户料号
                                        mesStockManage.setAreaCode(mesStorageWholesale.getAreaCode());
                                        mesStockManage.setLocationCode(mesStorageWholesale.getLocationCode());
                                        mesStockManageService.save(mesStockManage);
                                    }
                                } else {
                                    throw new RuntimeException("扫描入库编码不对！请检查！");
                                }
                            }
//                                    mesCertificateItemService.updateById(mesCertificateItem);
                            count++;
                        }
                    }
                }

            }
        }
        if (count != 0) {
            //扫描入库时，还需要扫描货架编码。并且设置货架状态为0
            //并且不是无货架扫描
            if (StringUtils.isNotBlank(mesStorageWholesale.getId()) && !"无货架入库".equals(mesStorageWholesale.getShelfCode())) {
                //亮灯两秒
                asyncUtils.asyncSleep(mesStorageWholesale.getShelfCode());
                //扫描货架编码。并且设置货架状态为0
                MesStorageWholesale storageWholesale = this.getById(mesStorageWholesale.getId());
                storageWholesale.setShelfCode(mesStorageWholesale.getShelfCode());
                storageWholesale.setShelfState("0");//设置货架状态为0:待发料
                this.updateById(storageWholesale);
            }

            //扫描入库后，设置query04为标签id，代表该标签已被扫描入库
            mesStorageWholesale.setQuery4(gId);//重复扫描检查
            mesStorageWholesale.setId(null);
            mesStorageWholesale.setCreateBy(sysUser.getUsername());//创建人设置
            mesStorageWholesale.setCreateTime(DateUtils.getDate());//创建时间设置
            this.save(mesStorageWholesale);

            //判断是否所有入库状态都“是”，则修改凭证抬头信息为入库已完成；
//                MesCertificatePerk mesCertificatePerk = mesCertificatePerkService.getById(baseRowNum);
//                mesCertificatePerk.setIfInput("入库完成");
//                mesCertificatePerkService.updateById(mesCertificatePerk);
            //执行方法
            long endTime = System.currentTimeMillis();
            float excTime = (float) (endTime - startTime) / 1000;
            System.out.println("执行addScanStoreAllmodify时间：" + excTime + "s");
            return true;
        } else {
            return false;
        }
    }

    @Transactional
    public void addScanStoremodify(MesStorageWholesale mesStorageWholesale,
                                   MesCertificateItem mesCertificateItem,
                                   String shelfCode, String pCode, String mCode, String docketType) {
        // 获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //扫描重复检查
        if (StringUtils.isNotBlank(shelfCode)) {
            //每扫描成功一个标签，则query04存入该标签的ID，代表该标签已经被扫描过
            String swId = mesStorageWholesale.getId();
            QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_code", pCode).eq("base_dockettype", docketType).eq("query4", swId);
            List<MesStorageWholesale> list = this.list(queryWrapper);
            if (list.size() > 0) {
                throw new RuntimeException("请勿重复扫描！");
            } else {
                if (StringUtils.isNotBlank(mesCertificateItem.getReserveCode())) {
                    BigDecimal inwareNum = new BigDecimal(mesStorageWholesale.getInwareNum());
                    String certificateId = mesCertificateItem.getReserveCode();
                    MesCertificateItem certificateItem = mesCertificateItemService.getById(certificateId);
                    BigDecimal totalNum = new BigDecimal(certificateItem.getUnstorageNum());
                    BigDecimal unstorageNum = totalNum.subtract(inwareNum);
                    if (unstorageNum.compareTo(BigDecimal.ZERO) == -1) {
                        throw new RuntimeException("入库数量不符！请检查！");
                    } else if (unstorageNum.compareTo(BigDecimal.ZERO) == 0) {
                        certificateItem.setIfStorage("是");
                        certificateItem.setUnstorageNum(unstorageNum.toString());
                        mesCertificateItemService.updateById(certificateItem);
                    } else {
                        certificateItem.setUnstorageNum(unstorageNum.toString());
                        mesCertificateItemService.updateById(certificateItem);
                    }
                }
                if (StringUtils.isNotBlank(mesStorageWholesale.getInwareNum())) {
                    BigDecimal inputNum = new BigDecimal(mesCertificateItem.getInputNum());//物料凭证已有数量
                    BigDecimal inwareNum = new BigDecimal(mesStorageWholesale.getInwareNum());//标签上的数量
                    BigDecimal newInputNum = inputNum.add(inwareNum);//凭证新数量=已有数量+标签上的数量
                    mesCertificateItem.setInputNum(newInputNum.toString());
                    mesCertificateItem.setUnstorageNum(newInputNum.toString());//未入库数量=凭证新数量
                    //106 扫描入库
                    if (mesCertificateItem.getMobileCode().equals("106")) {
                        QueryWrapper<MesStockManage> wrapper = new QueryWrapper<>();
                        wrapper.eq("materiel_code", mCode);
                        MesStockManage stockManage = mesStockManageService.getOne(wrapper);
                        if (stockManage != null) {
                            if (StringUtils.isNotBlank(stockManage.getStockNum())) {
                                BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());
                                BigDecimal totalNum = stockNum.add(inwareNum);
                                stockManage.setStockNum(totalNum.toString());
                                mesStockManageService.updateById(stockManage);
                            } else {
                                throw new RuntimeException("料号为 " + mesCertificateItem.getMaterielCode() + "的" + mesCertificateItem.getMaterielName() + "库存数量不能为空！");
                            }
                        } else {
                            MesStockManage mesStockManage = new MesStockManage();
                            BeanUtils.copyProperties(mesCertificateItem, mesStockManage);
                            mesStockManage.setId(null);//主键设置为null
                            mesStockManage.setCreateBy(sysUser.getUsername());//创建人设置
                            mesStockManage.setCreateTime(DateUtils.getDate());//创建时间设置
                            mesStockManage.setStoreName(mesCertificateItem.getStorageSite());
                            mesStockManage.setUnit(mesCertificateItem.getInputUnit());
                            mesStockManage.setStockNum(inwareNum.toString());
                            mesStockManage.setQuery5(mesStorageWholesale.getRowNum());
                            mesStockManageService.save(mesStockManage);
                        }
                    }
                }
                mesCertificateItemService.updateById(mesCertificateItem);
            }

        }/*else {
						return Result.error("货架编码不能为空！");
					}*/
        //扫描入库时，还需要扫描货架编码。并且设置货架状态为0
        //并且不是无货架扫描
        if (StringUtils.isNotBlank(mesStorageWholesale.getId()) && !"无货架入库".equals(shelfCode)) {
            //扫描到的货架异步执行亮红灯2秒
            String shelfCode1 = mesStorageWholesale.getShelfCode();//扫描到的货架编码
            asyncUtils.asyncSleep(shelfCode1);

            //扫描货架编码。并且设置货架状态为0
            MesStorageWholesale storageWholesale = this.getById(mesStorageWholesale.getId());
            storageWholesale.setShelfCode(shelfCode);
            storageWholesale.setShelfState("0");//设置货架状态为0:待发料
            this.updateById(storageWholesale);
        }
        //扫描入库后，设置query04为标签id，代表该标签已被扫描入库
        mesStorageWholesale.setQuery4(mesStorageWholesale.getId());//重复扫描检查
        mesStorageWholesale.setId(null);
        mesStorageWholesale.setCreateBy(sysUser.getUsername());//创建人设置
        mesStorageWholesale.setCreateTime(DateUtils.getDate());//创建时间设置
        this.save(mesStorageWholesale);
    }

    public synchronized boolean addScanStore(MesStorageWholesale mesStorageWholesale) {

        if (StringUtils.isNotBlank(mesStorageWholesale.getProductCode()) &&
                StringUtils.isNotBlank(mesStorageWholesale.getBaseRownum()) &&
                StringUtils.isNotBlank(mesStorageWholesale.getBaseDockettype())) {
            String pCode = mesStorageWholesale.getProductCode();//产品编号：料号
            System.err.println(pCode);
            String baseRowNum = mesStorageWholesale.getBaseRownum();//基本行号：物料凭证项目id

            //通过物料凭证项目id,获取物料凭证项目的数据
            MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
            if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {
                String mCode = mesCertificateItem.getMaterielCode();//物料料号
                String docketType = mesStorageWholesale.getBaseDockettype();//单据类型
                System.err.println(mCode);
                //如果产品编号和物料凭证的料号不符，则扫描到错误的标签
                if (!pCode.equals(mCode)) {
                    throw new RuntimeException("扫描的物料不符！请检查！");
                } else {

                    String shelfCode = mesStorageWholesale.getShelfCode();//货架编号
                    if (!"无货架入库".equals(mesStorageWholesale.getShelfCode())) {
                        //验证货架是否状态为0，待发料
                        QueryWrapper<MesStorageWholesale> storageQueryWrapper = new QueryWrapper<>();
                        storageQueryWrapper.eq("shelf_code", shelfCode);
                        storageQueryWrapper.eq("base_dockettype", "收货打印");
                        storageQueryWrapper.eq("shelf_state", "0");
                        List<MesStorageWholesale> list1 = this.list(storageQueryWrapper);
                        if (list1.size() > 0) {
                            throw new RuntimeException("该货位已有物品，请核实！");
                        }
                    }
                    addScanStoremodify(mesStorageWholesale, mesCertificateItem, shelfCode, pCode, mCode, docketType);
                }
            }
        } else {
            throw new RuntimeException("找不到数据！请检查！");
        }
        return true;
    }

    /**
     * 根据query4查询该制令单的上料记录 并根据原有上料记录去转产数量记录 远程调用
     *
     * @param query4   原制令单id
     * @param synum    已使用数量
     * @param mcode    物料料号
     * @param basecode 转产的制令单bom的id
     * @param newid    转产的制令单id
     * @return
     */
    public String updateCommandbill(String query4, String synum, String mcode, String basecode, String newid) {
        QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("base_dockettype", "扫描上料");
        queryWrapper.eq("query4", query4);
        queryWrapper.eq("product_code", mcode);
        queryWrapper.orderByAsc("create_time");
        List<MesStorageWholesale> list = this.list(queryWrapper);

        BigDecimal consumeNum = new BigDecimal(synum);//已消耗数量
        //入库数量
        BigDecimal inwareNum = BigDecimal.ZERO;
        BigDecimal wareNum = BigDecimal.ZERO;//转产上料数量
        int iii = 0;
        for (int i = 0; i < list.size(); i++) {
            MesStorageWholesale stinfo = list.get(i);
//			System.out.println("入库数量: "+i+": "+saleinfo.getInwareNum());
            BigDecimal bigDecimal = new BigDecimal(stinfo.getInwareNum());//入库数量
            inwareNum = inwareNum.add(bigDecimal);//每次都加上入库数量
            if (consumeNum.compareTo(inwareNum) < 1) {//consumeNum已消耗数量 小于等于 inwareNum入库数量
                if (iii == 0) {
                    iii++;
                    //已使用数量减入库数量
                    BigDecimal wareNum1 = inwareNum.subtract(consumeNum);
                    wareNum = wareNum1;
                    stinfo.setInwareNum(wareNum1.toString());
                } else {
                    wareNum = wareNum.add(bigDecimal);
                }
                stinfo.setBaseCode(basecode);
                stinfo.setQuery5("批量转产上料,原制令单id：" + query4);
                stinfo.setQuery4(newid);
                stinfo.setId(null);
                stinfo.setCreateTime(null);
                stinfo.setCreateBy(null);
                this.save(stinfo);
            }
        }
        return wareNum.toString();
    }

    //原材料入库单
    @Override
    public Page<ReportVo> selectYclRkd(Page<ReportVo> page, String begindate, List<String> ids, String attr1) {
        long startTime = System.currentTimeMillis();
        Page<ReportVo> reportVoPage = page.setRecords(mesStorageWholesaleMapper.selectYclRkd(page, begindate, ids, attr1));
        long endTime = System.currentTimeMillis();
        float excTime = (float) (endTime - startTime) / 1000;
        System.out.println("执行selectYclRkd时间：" + excTime + "s");
        return reportVoPage;
    }

    //成品入库单
    @Override
    public Page<ReportVo> selectCpRkd(Page<ReportVo> page, String begindate, List<String> attr1, String attr2, String attr4) {
        return page.setRecords(mesStorageWholesaleMapper.selectCpRkd(page, begindate, attr1, attr2, attr4));
    }

    //成品出库单
    @Override
    public Page<ReportVo> selectCpChd(Page<ReportVo> page, String begindate,  List<String> attr1, String attr2, String attr4) {
        return page.setRecords(mesStorageWholesaleMapper.selectCpChd(page, begindate, attr1, attr2, attr4));
    }

    //生产领料单
    @Override
    public Page<ReportVo> selectLld(Page<ReportVo> page, String commadid) {
        return page.setRecords(mesStorageWholesaleMapper.selectLld(page, commadid));
    }

    //退料单
    @Override
    public Page<ReportVo> selectTld(Page<ReportVo> page, String commadid) {
        return page.setRecords(mesStorageWholesaleMapper.selectTld(page, commadid));
    }

    //原材料进销存
    @Override
    public Page<ReportVo> selectYclJxc(Page<ReportVo> page, String materid, String areaCode, String locationCode) {
        return page.setRecords(mesStorageWholesaleMapper.selectYclJxc(page, materid, areaCode, locationCode));
    }

    //导出原材料进销存
    @Override
    public List<ReportVo> exportXlsYclJxc(YclJxcReportVO vo) {
        return mesStorageWholesaleMapper.exportXlsYclJxc(vo.getMaterid(), vo.getAreaCode(), vo.getLocationCode(), vo.getIds());
    }

    //原材料流水报表
    @Override
    public Page<ReportVo> selectLsbb(Page<ReportVo> page, String materid, String areaCode, String locationCode) {
        return page.setRecords(mesStorageWholesaleMapper.selectLsbb(page, materid, areaCode, locationCode));
    }

    //成品进销存
    @Override
    public Page<ReportVo> selectCpJxc(Page<ReportVo> page, String materid, String areaCode, String locationCode) {
        return page.setRecords(mesStorageWholesaleMapper.selectCpJxc(page, materid, areaCode, locationCode));
    }

    /**
     * 拆分板-根据批号ID查询拆分板
     */
    @Override
    public Result<?> findSplitBoard(String id) {
        if (StringUtils.isBlank(id)) {
            return Result.error("获取查询参数失败！");
        }
        QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeLeft("base_dockettype", "拆板打印");
        queryWrapper.eq("query5", id);
        List<MesStorageWholesale> list = mesStorageWholesaleMapper.selectList(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 盘点入库-根据批号ID查询物料入库
     */
    @Override
    public Result<?> checkStockInById(String id) {
        log.info("盘点入库入参:checkStockInById>>id>" + id);
        //验证该批号交易是否入库
        MesStorageWholesale mesStorageWholesale = mesStorageWholesaleMapper.selectById(id);
        log.info("盘点入库:checkStockInById>>mesStorageWholesale>" + JSON.toJSONString(mesStorageWholesale));
        MesStockManage mesStockManage = mesStockManageService.getStockManageByMaterielCode(mesStorageWholesale.getProductCode());
        log.info("盘点入库:checkStockInById>>mesStockManage>" + JSON.toJSONString(mesStockManage));
        if (com.epms.util.ObjectHelper.isNotEmpty(mesStockManage)) {
            BigDecimal stockNum = new BigDecimal(StringUtils.isNotBlank(mesStockManage.getStockNum()) ? mesStockManage.getStockNum() : "0");
            BigDecimal inWareNum = new BigDecimal(StringUtils.isNotBlank(mesStorageWholesale.getInwareNum()) ? mesStorageWholesale.getInwareNum() : "0");
            mesStockManage.setStockNum(stockNum.add(inWareNum).toString());
            log.info("盘点入库修改前:checkStockInById>>mesStockManage>" + JSON.toJSONString(mesStockManage));
            if (mesStockManageService.updateById(mesStockManage)) {
                //添加批号交易扫描入库记录
                return Result.ok("修改库存成功！");
            } else {
                return Result.error("修改库存失败！");
            }
        } else {
            if (mesStockManageService.save(setMesStockManage(mesStorageWholesale, mesStockManage))) {
                //添加批号交易扫描入库记录
                return Result.ok("添加库存成功！");
            } else {
                return Result.error("添加库存失败！");
            }
        }
    }

    /**
     * 入库单报表导出
     */
    @Override
    public List<YclRkdReport> exportYclRkd(YclRkdReportVO vo) {
        return mesStorageWholesaleMapper.exportYclRkd(vo.getBegindate(), vo.getAttr1(), vo.getIds());
    }

    /**
     * 初始化入库信息
     */
    private MesStockManage setMesStockManage(MesStorageWholesale mesStorageWholesale, MesStockManage mesStockManage) {
        log.info("初始化入库信息入参:checkStockInById>>setMesStockManage>" + JSON.toJSONString(mesStorageWholesale));
        log.info("初始化入库信息入参:checkStockInById>>mesStockManage>" + JSON.toJSONString(mesStockManage));
        // 获取登录用户信息
        mesStockManage.setId(null);
        mesStockManage.setCreateBy(mesStorageWholesale.getCreateBy());//创建人
        mesStockManage.setSysOrgCode(mesStorageWholesale.getSysOrgCode());//所属部门
        mesStockManage.setMaterielCode(mesStorageWholesale.getProductCode());//物料料号
        mesStockManage.setMaterielName(mesStorageWholesale.getProductName());//物料名称
        mesStockManage.setFactoryCode(mesStorageWholesale.getAreaCode());//工厂编号
        mesStockManage.setFactoryName(mesStorageWholesale.getQuery2());//工厂名称
        mesStockManage.setStoreName(mesStorageWholesale.getWareSite());//仓库名称
        mesStockManage.setStockNum(mesStorageWholesale.getInwareNum());//库存数量
        mesStockManage.setUnit(mesStorageWholesale.getUnit());//单位
        log.info("初始化入库信息反参:checkStockInById>>mesStockManage>" + JSON.toJSONString(mesStockManage));
        return mesStockManage;
    }

    /**
     * app扫描上料
     *
     * @param mesStorageWholesale
     * @return
     */
    @CacheEvict(value = CacheConstant.WAREHOUSE_SELECT_QUERY4_SL, key = "#p0.query4")
    public void addUnglaze(MesStorageWholesale mesStorageWholesale) {
        System.out.println("app扫描上料(清楚缓存):" + mesStorageWholesale);
        this.save(mesStorageWholesale);
    }

    /**
     * app扫描发料
     *
     * @param mesStorageWholesale
     * @return
     */
    public Result<?> scanSendMateriel(@RequestBody MesStorageWholesale mesStorageWholesale) {
        System.err.println(mesStorageWholesale);
        String query4 = mesStorageWholesale.getQuery4();//制令单id
        // 获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        lock.lock(); // 获取锁对象
        try {

            if (StringUtils.isNotBlank(mesStorageWholesale.getProductCode()) && StringUtils.isNotBlank(mesStorageWholesale.getBaseRownum()) && StringUtils.isNotBlank(mesStorageWholesale.getBaseDockettype())) {
                //基本行号：物料凭证项目id
                String pCode = mesStorageWholesale.getProductCode();
                System.err.println(pCode);
                String baseRowNum = mesStorageWholesale.getBaseRownum();
                MesCommandbillInfo commandbillinfo = produceClient.getById(query4);
                MesWarehouseArea mesWarehouseArea = iMesWarehouseAreaService.getMesWarehouseAreaByClientName(commandbillinfo.getClientName());
                if (com.epms.util.ObjectHelper.isEmpty(mesWarehouseArea)) {
                   throw new RuntimeException("该制令单的客户名称未找到对应的库区库位，请检查！");
                }else{
                    mesStorageWholesale.setLocationCode(mesWarehouseArea.getAreaLocations().get(0).getLocationCode());
                    mesStorageWholesale.setAreaCode(mesWarehouseArea.getAreaCode());
                }
                MesCommandbillPitem commandbillPitem1 = produceClient.queryPitemById(mesStorageWholesale.getBaseCode());//制令单bomitem信息
                MesCertificateItem mesCertificateItem = mesCertificateItemService.getById(baseRowNum);
                if (mesCertificateItem != null && StringUtils.isNotBlank(mesCertificateItem.getMaterielCode())) {
                    String mCode = mesCertificateItem.getMaterielCode();//凭证项目物料料号
                    //替代料验证
                    List<MesChiefdataReplacematerial> replacematerials = systemClient.queryReplaceCode(commandbillinfo.getMechanismCode(), mCode, pCode);
                    /*System.out.println("替代料："+commandbillinfo.getMechanismCode()+"==="+mCode+"==="+pCode);
                    replacematerials.forEach(System.out::println);*/
                    if (!pCode.equals(mCode) && replacematerials.size() == 0) {
                        return Result.error("扫描的物料不符！请检查！");
                    } else {
                        if (replacematerials.size() > 0) {
                            //上料记录设置为主料料号
                            mesStorageWholesale.setProductCode(mCode);
                            mesStorageWholesale.setQuery3("替代料:" + pCode);
                        }
                        //扫描重复检查
                        if (StringUtils.isNotBlank(mesStorageWholesale.getQuery5())) {
                            QueryWrapper<MesStorageWholesale> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("query5", mesStorageWholesale.getQuery5());
                            MesStorageWholesale storageWholesale = this.getOne(queryWrapper);
                            if (storageWholesale != null) {
                                return Result.error("请勿重复扫描！");
                            } else {
                                //扫描发料，避免料架的物料被重复扫描
                                if (StringUtils.isNotBlank(mesStorageWholesale.getShelfCode())
                                        && StringUtils.isNotBlank(mesStorageWholesale.getShelfState())) {
                                    if (mesStorageWholesale.getShelfState().equals("1")) {
                                        return Result.error("货架上的物料已经被扫描过！请检查！");
                                    }
                                }
                                MesCommandbillPitem commandbillPitem = produceClient.queryPitemById(mesStorageWholesale.getBaseCode());
                                if (commandbillPitem != null && mesStorageWholesale.getBaseDockettype().equals("扫描发料")) {
                                    BigDecimal printNum = new BigDecimal(mesStorageWholesale.getInwareNum());//打印标签上的数量
                                    String orderId = commandbillPitem.getProorderId();//生产订单id
                                    //制令单发料可以超发，先扣除领料单领取的数量；若超过领料数量，再从库存里扣除
                                    QueryWrapper<MesMaterielOccupy> materielOccupyWrapper = new QueryWrapper<>();
                                    materielOccupyWrapper.eq("order_id", orderId).eq("materiel_code", pCode);
                                    MesMaterielOccupy mesMaterielOccupy = mesMaterielOccupyService.getOne(materielOccupyWrapper);
                                    //领料记录是空的则新增领料记录
                                    if (mesMaterielOccupy == null) {
                                        mesMaterielOccupy = new MesMaterielOccupy();
                                        mesMaterielOccupy.setOrderId(orderId);
                                        MesOrderProduce mesOrderProduce = transactionClient.queryBysId(orderId);
                                        if (mesOrderProduce != null) {
                                            mesMaterielOccupy.setOrderCode(mesOrderProduce.getOrderCode());
                                            mesMaterielOccupy.setOrderName(mesOrderProduce.getOrderName());
                                        }
                                        mesMaterielOccupy.setMaterielCode(pCode);
                                        mesMaterielOccupy.setMaterielName(mesCertificateItem.getMaterielName());
                                        mesMaterielOccupy.setMaterielGague(mesCertificateItem.getMaterielGauge());
                                        if (commandbillPitem1 != null) {
                                            mesMaterielOccupy.setOccupyNum(commandbillPitem1.getRequireNum());
                                        }
                                        mesMaterielOccupy.setUnusedNum("0");
                                        mesMaterielOccupy.setWithdrawNum("0");
                                        mesMaterielOccupy.setTransformNum("0");
                                        mesMaterielOccupyService.save(mesMaterielOccupy);
                                    }
                                    if (mesMaterielOccupy != null) {
                                        BigDecimal unUsedNum = new BigDecimal(mesMaterielOccupy.getUnusedNum());//未使用数量
                                        BigDecimal deliveryNum = new BigDecimal(commandbillPitem.getDeliveryNum()); //已发料数量
                                        if (unUsedNum.compareTo(printNum) == -1) {//物料超发
                                            BigDecimal usedStockNum = printNum.subtract(unUsedNum);//超发的数量
                                            //                                        QueryWrapper<MesStockManage> wrapper = new QueryWrapper<>();
                                            //                                        wrapper.eq("materiel_code", pCode);
                                            //                                        MesStockManage stockManage = mesStockManageService.getOne(wrapper);
                                            MesStockManage stockManage = new MesStockManage();
                                            try {
                                                stockManage = mesStockManageService.queryByMcodeAndClient(pCode, commandbillinfo.getClientName());
                                            }catch (Exception e){
                                                return Result.error("未在库存中找到该客户该物料信息！");
                                            }
                                            if (stockManage == null) {
                                                return Result.error("查不到库存数据！请检查！");
                                            } else {
                                                BigDecimal stockNum = new BigDecimal(stockManage.getStockNum());//库存数量
                                                BigDecimal minimum = new BigDecimal(stockManage.getMinimum());//库存临界点
                                                BigDecimal remainNum = stockNum.subtract(usedStockNum);//剩余数量=库存数量-超发数量
                                                //如果库存数量小于0，则提示库存数量不足。反之，将剩余数量，更新到库存上
                                                if (remainNum.compareTo(BigDecimal.ZERO) == -1) {
                                                    return Result.error("库存数量不足！请检查！");
                                                } else {
                                                    stockManage.setStockNum(remainNum.toString());//新的库存数量 = 剩余数量
                                                    mesStockManageService.updateById(stockManage);
                                                    //如果库存数量小于库存临界点，则给用户发送消息提醒
                                                    if (remainNum.compareTo(minimum) < 1) {
                                                        // 获取登录用户信息
                                                        System.err.println(sysUser);
                                                        //测试时，向当前登录用户发送消息提醒；正式上线后，需要向采购人员（溢哲渝设定）发送库存临界点警告
                                                        systemClient.sendMessage(sysUser.getUsername(), stockManage.getMaterielName());
                                                    }
                                                    BigDecimal num = deliveryNum.add(printNum);//新的发料数量 = 原有数量+ 打印标签上的数量（发料数量）
                                                    commandbillPitem.setDeliveryNum(num.toString());
                                                    commandbillPitem.setIfGlaze("未上料");
                                                    produceClient.editComitem(commandbillPitem);
                                                    //更新领料表数据
                                                    mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                                    mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                                    mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                                                    mesMaterielOccupy.setUnusedNum("0");
                                                    mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                                }
                                            }
                                        } else {//未超发
                                            BigDecimal remainNum = unUsedNum.subtract(printNum);//剩余数量 = 未领用数量- 打印标签上的数量（发料数量）
                                            BigDecimal num = deliveryNum.add(printNum);//新的已发料数量 = 原有数量+ 打印标签上的数量（发料数量）
                                            commandbillPitem.setDeliveryNum(num.toString());
                                            commandbillPitem.setIfGlaze("未上料");
                                            produceClient.editComitem(commandbillPitem);
                                            //更新领料表数据
                                            mesMaterielOccupy.setOccupyPerson(sysUser.getUsername());//发料人
                                            mesMaterielOccupy.setSendNum(num.toString());//发料数量
                                            mesMaterielOccupy.setOccupyTime(new Date());//发料时间
                                            mesMaterielOccupy.setUnusedNum(remainNum.toString());//未使用数量
                                            mesMaterielOccupyService.updateById(mesMaterielOccupy);
                                        }
                                    } else {
                                        return Result.error("找不到物料领用数据！请检查！");
                                    }
                                } else {
                                    return Result.error("找不到制令单BOM的相关数据！请检查！");
                                }
                            }
                        } else {
                            return Result.error("扫描的二维码为空！请检查！");
                        }
                    }
                }
            } else {
                return Result.error("找不到数据！请检查！");
            }
            mesStorageWholesale.setId(null);//主键设置为null
            mesStorageWholesale.setCreateBy(sysUser.getUsername());//创建人设置
            mesStorageWholesale.setCreateTime(DateUtils.getDate());//创建时间设置
            this.save(mesStorageWholesale);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); // 释放锁对象
        }
        return Result.ok("扫描发料成功");
    }

    /**
     * 查询该采购子表id的收货数量
     *
     * @param id
     * @return
     */
    public int queryPurchaseItemSum(String id) {
        return mesStorageWholesaleMapper.queryPurchaseItem(id);
    }

    /**
     * 查询出还未收货的已打印物料的id
     *
     * @param baseCode 采购订单子表id
     * @return
     */
    public List<MesStorageWholesale> selectPrintUnreceivelist(String baseCode) {
        return mesStorageWholesaleMapper.selectPrintUnreceivelist(baseCode);
    }

    /**
     * 打印了还未收货的数量
     *
     * @param baseCode 采购订单子表id
     * @return
     */
    public int queryPrintUnreceiveNum(String baseCode) {
        transactionClient.uploadUnreceiveNum(baseCode);
        return mesStorageWholesaleMapper.queryPrintUnreceiveNum(baseCode);
    }

    @Override
    public String getSumByInWareNum(String id) {
        int inWareNum = mesStorageWholesaleMapper.getSumByInWareNum(id);
        return Integer.toString(inWareNum);
    }

    /**
     * 获取扫描上料记录 根据旧料盘id查询
     */
    public List<MesStorageWholesale> getshangliao(String id){
        if (StringUtils.isBlank(id)){
            throw new RuntimeException("旧料盘id不能为空！");
        }
        LambdaQueryWrapper<MesStorageWholesale> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(MesStorageWholesale::getGlazeId,id);
        List<MesStorageWholesale> selectList = mesStorageWholesaleMapper.selectList(lambdaQuery);
        return selectList;
    }
}
